import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { CredentialsDto } from 'src/app/shared/services/http/dto/credentials.dto';
import { TokensService } from 'src/app/shared/services/http/tokens.service';
import { LocalStorageService } from 'src/app/shared/services/local-storage/local-storage.service';
import { TOKEN } from 'src/app/shared/services/local-storage/local-storage.namespace';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private tokensService: TokensService,
    private localStorageService: LocalStorageService,
    public router: Router,
  ) {
    this.loginForm = this.formBuilder.group({
      account: '',
      password: '',
    } as CredentialsDto);
  }

  ngOnInit(): void {}

  /**
   * 提交登录表单
   * @param credentialsDto 凭据
   */
  onSubmit(credentialsDto: CredentialsDto) {
    this.tokensService.create(credentialsDto).subscribe(
      ({ token }) => {
        this.localStorageService.set(TOKEN, token);
        this.router.navigateByUrl('/');
      },
      ({ error: { error, message } }) => {
        console.log(error, message);
      },
    );
  }
}
